package ar.edu.utn.frsf.tpae.a2013.g02.persistence.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import ar.edu.utn.frsf.tpae.a2013.g02.persistence.dao.CentroCostoDao;
import ar.edu.utn.frsf.tpae.a2013.g02.persistence.model.CentroCosto;

/**
 * DAO de CentroCosto basado en Hibernate.
 * 
 * @author TPAE
 */
public class CentroCostoHibernetDao implements CentroCostoDao {

	private static SessionFactory sessionFactory = configureSessionFactory();
	private static ServiceRegistry serviceRegistry;

	private static SessionFactory configureSessionFactory()
			throws HibernateException {
		Configuration configuration = new Configuration();
		configuration.configure();
		serviceRegistry = new ServiceRegistryBuilder().applySettings(
				configuration.getProperties()).buildServiceRegistry();
		sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		return sessionFactory;
	}

	@Override
	public CentroCosto persistir(CentroCosto centroCosto) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.saveOrUpdate(centroCosto);
		session.getTransaction().commit();
		session.close();
		return centroCosto;
	}

	@Override
	public void eliminar(CentroCosto centroCosto) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.delete(centroCosto);
		session.getTransaction().commit();
		session.close();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CentroCosto> listar() {
		Session session = sessionFactory.openSession();
		Query query = session
				.createQuery("from " + CentroCosto.class.getName());
		return query.list();
	}

	@Override
	public CentroCosto buscarPorId(Integer id) {
		Session session = sessionFactory.openSession();
		return (CentroCosto) session.get(CentroCosto.class, id);
	}

	// @Override
	// public CentroCosto buscarPorNumero(String numero) {
	// Session session = sessionFactory.openSession();
	// Query query = session.createQuery("select from " +
	// CentroCosto.class.getName()
	// + " where numero = :numero");
	// query.setString("numero", numero);
	// return (CentroCosto) query.uniqueResult();
	// }

}